<?php
/**
 * Created by PhpStorm.
 * User: TS
 * Date: 2017/4/4
 * Time: 20:26
 */
namespace core;

class Service {

    protected static $instance = [];

    protected $baseUrl;
    public $ch = null;
    private $method = 'post';

    /**
     * Service constructor.
     * @param $baseUrl
     */
    public function __construct($baseUrl)
    {
        $this->baseUrl = $baseUrl;
        $this->ch = curl_init();
    }

    /**
     * @param $baseUrl
     * @return static
     */
    public static function getInstance($baseUrl)
    {
        $baseUrl = rtrim($baseUrl, '/') . '/';
        $uuid = md5($baseUrl);
        if (!isset(self::$instance[$uuid])) {
            self::$instance[$uuid] = new static($baseUrl);
        }
        return self::$instance[$uuid];
    }

    /**
     * @param $method
     * @return $this
     */
    public function setMethod($method = 'post')
    {
        $this->method = $method;
        return $this;
    }

    /**
     * @param $url
     * @param  array $param
     * @return mixed
     */
    public function send($url, array $param = [])
    {
        if( 'post' == strtolower($this->method))
            return $this->post($url, $param);
        else
            return $this->get($url, $param);
    }

    /**
     * @param $url
     * @param $post_data
     * @return mixed
     */
    public function post($url, $post_data = [])
    {
        curl_setopt( $this->ch, CURLOPT_URL, $this->baseUrl . $url);
        curl_setopt( $this->ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $this->ch, CURLOPT_HEADER, 0 );
        curl_setopt($this->ch, CURLOPT_POST, 1);
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec( $this->ch );
        return $output;
    }

    /**
     * @param $url
     * @param $get_data
     * @return mixed
     */
    public function get($url, $get_data = [])
    {
        $url = $this->baseUrl . $url.'?'.http_build_query($get_data);
        curl_setopt( $this->ch, CURLOPT_URL, $url );
        curl_setopt( $this->ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $this->ch, CURLOPT_HEADER, 0 );
        $output = curl_exec( $this->ch );
        return $output;
    }
}